//
//  AnimeAction.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/9.
//

import Foundation
import HandyJSON
import Moya
import PKHUD
import ProgressHUD
import ReSwift
import ReSwiftThunk

enum HTEnumAnimeAction: Action {
    case htEnumHomeSubjects(var_subjects: [HTSubject]?)
    case htEnumSubjectList(var_subjectList: [HTAnime]?)
    case htEnumAnimeInfo(var_animeAll: HTAnimeAll?)
    case htEnumAnimeUrls(var_animeUrls: [HTServer]?)

    // 获取首页数据
    static func ht_homeData(id: String?, andCallback: (([HTSubject]?) -> Void)?) -> Thunk<HTAppState> {
        Thunk<HTAppState> { _, _ in
            HUD.show(.progress)
            HTNetworkManager().ht_request(.htEnumHomeData(var_id: id ?? "", var_p1: "3")) { result in
                HUD.hide()
                if result.var_status == "200" {
                    let var_data = result.ht_data()
                    let var_defaultSet = HTDefaultSet.deserialize(from: var_data, designatedPath: "default_set")

                    if andCallback != nil {
                        andCallback!(var_defaultSet?.var_subjects ?? [])
                    }
                    HTNetworkManager().ht_requestForBuried(.htEnumHomeMShNew(var_loadsuccess: "1", var_like_list: "1"))
                } else {
                    HTNetworkManager().ht_requestForBuried(.htEnumHomeMShNew(var_loadsuccess: "4", var_errorinfo: result.var_message ?? ""))
                }
            }
        }
    }

    // 获取专题列表信息
    static func ht_subjectList(params: [String: String], andCallback: (([HTAnime]?) -> Void)?) -> Thunk<HTAppState> {
        Thunk<HTAppState> { _, _ in
            HTNetworkManager().ht_request(.htEnumSubjectList(var_id: params["id"] ?? "", var_page: params["page"] ?? "", var_page_size: params["page_size"] ?? "", var_orderby: "1", var_type: "1", var_genre: "100", var_g2: "100", var_pubdate: "100")) { result in
                let var_data = result.ht_data()
                let var_filter_ainfo = [HTAnime].deserialize(from: var_data, designatedPath: "filter_ainfo") as? [HTAnime]
                if andCallback != nil {
                    andCallback!(var_filter_ainfo ?? [])
                }
            }
        }
    }

    // 意见反馈
    static func ht_feedback(content: String, andMail: String, andCallback: (() -> Void)?) -> Thunk<HTAppState> {
        Thunk<HTAppState> { _, _ in
            ProgressHUD.animate()
            HTNetworkManager().ht_request(.htEnumFeedback(var_content: content, var_mail: andMail)) { _ in
                ProgressHUD.succeed(delay: 1.0)
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    if andCallback != nil {
                        andCallback!()
                    }
                }
            }
        }
    }

    // 获取播放历史记录
    static func ht_recentPlayList(callback: (([HTAnime]?) -> Void)?) -> Thunk<HTAppState> {
        Thunk<HTAppState> { _, _ in
            let var_recentPlay = HTCoreDataManager().ht_fetchRecentPlayData()
            var var_recentPlay_json: [Any] = []
            for recentPlay in var_recentPlay {
                var var_params: [String: Any] = [:]
                var_params["id"] = recentPlay.id
                var_params["cover"] = recentPlay.cover
                var_params["title"] = recentPlay.title
                var_params["ep"] = recentPlay.ep
                var_params["cur_ep"] = recentPlay.cur_ep
                var_params["cur_epId"] = recentPlay.cur_epId
                var_params["progressRate"] = recentPlay.progressRate
                var_params["startTime"] = recentPlay.startTime
                var_params["during"] = recentPlay.during

                var_recentPlay_json.append(var_params)
            }
            let var_animes = [HTAnime].deserialize(from: var_recentPlay_json) as? [HTAnime]
            if callback != nil {
                callback!(var_animes)
            }
        }
    }

    // 添加播放历史
    static func ht_addRecentPlay(anime: HTAnime) -> Thunk<HTAppState> {
        Thunk<HTAppState> { _, _ in
            HTCoreDataManager().ht_addNewRecentPlay(anime: anime)
            NotificationCenter.default.post(name: HTConfig.STATIC_notification_addNewRecentPlay, object: nil, userInfo: nil)
        }
    }

    // 删除播放历史
    static func ht_deleteRecentPlay(ids: [String]) -> Thunk<HTAppState> {
        Thunk<HTAppState> { _, _ in
            HTCoreDataManager().ht_deleteRecentPlay(ids: ids)
        }
    }

    // 获取动漫详情
    static func ht_animeInfo(params: [String: String], andCallback: ((HTAnimeAll?) -> Void)?) -> Thunk<HTAppState> {
        Thunk<HTAppState> { _, _ in
            HUD.show(.progress)
            HTNetworkManager().ht_request(.htEnumAnimeInfo(var_id: params["id"] ?? "", var_uid: params["uid"] ?? "")) { result in
                HUD.hide()
                if result.var_status == "200" {
                    let var_data = result.ht_data()
                    let var_list = result.ht_list()
                    let var_anime_info = HTAnime.deserialize(from: var_data, designatedPath: "")
                    let var_anime_recommend = [HTRecommend].deserialize(from: var_list, designatedPath: "") as? [HTRecommend]
                    let var_all: HTAnimeAll = HTAnimeAll(var_info: var_anime_info, var_reco: var_anime_recommend)
                    if andCallback != nil {
                        andCallback!(var_all)
                    }
                } else {
                    HUD.flash(.labeledError(title: "", subtitle: result.var_message ?? ""), delay: 1.0)
                }
            }
        }
    }

    // 获取url
    static func ht_animeUrls(params: [String: String], andCallback: (([HTServer]?) -> Void)?) -> Thunk<HTAppState> {
        Thunk<HTAppState> { _, _ in
            HTNetworkManager().ht_request(.htEnumAnimeUrl(var_id: params["id"] ?? "", var_sig: params["sig"] ?? "", var_unixtime: params["unixtime"] ?? "")) { result in
                if result.var_status == "200" {
                    let var_data = result.ht_data()
                    let var_urls = var_data?.ht_toDict().ht_urls()
                    if andCallback != nil {
                        andCallback!(var_urls)
                    }
                } else {
                    HUD.flash(.labeledError(title: "", subtitle: result.var_message ?? ""), delay: 1.0)
                }
            }
        }
    }

    // 获取字幕
    static func ht_subtitle(params: [String: String], andCallback: (([HTSub]?) -> Void)?) -> Thunk<HTAppState> {
        Thunk<HTAppState> { _, _ in
            HTNetworkManager().ht_request(.htEnumAnimeSubtitle(var_id: params["id"] ?? "", var_type: params["type"] ?? "")) { result in
                let var_data = result.ht_data()
                let var_subs = [HTSub].deserialize(from: var_data, designatedPath: "subtitle") as? [HTSub]

                if andCallback != nil {
                    andCallback!(var_subs)
                }
            }
        }
    }
}
